//
//  MedicineDetailController.swift
//  YiYaoHui
//
//  Created by 高永效 on 15/12/3.
//  Copyright © 2015年 EgeTart. All rights reserved.
//

import UIKit
import Alamofire
import MBProgressHUD

class MedicineDetailController: UIViewController {

    
    @IBOutlet weak var detailTableView: UITableView!
    
    @IBOutlet weak var titleItem: UINavigationItem!
    
    var medicineType = ""
    var medicineID = ""
    var medicineName = ""
    
    let db = MedicineDB.sharedInstance()
    
    //数据库中西药
    var titles = [String]()
    var contents = [String]()
    
    //企业西药
    var westernTitles = [String]()
    var westernContents = [String]()
    
    //企业中药
    var traditionTitles = [String]()
    var traditionContents = [String]()
    
    var menuIsShow = false
    
    var id = 1 //2:企业药品请求过来的
    var enterpriseMedicineType = 5 //中药3；西药4 ;5 随便定的初始化
    var enterpriseWesternMedicine = [EnterpriseDetailWesternMedicine]()
    var enterpriseTraditionMedicine = [EnterpriseDetailTraditionMedicine]()
    
    lazy var optionsTableView: UIView! = {
        let tableView: UITableView = UITableView(frame: CGRect(x: 0.0, y: 0.0, width: 135.0, height: CGFloat(44 * 8)))
        tableView.tableFooterView = UIView(frame: CGRectZero)
        tableView.separatorStyle = .None
        tableView.tag = 501
        tableView.dataSource = self
        tableView.delegate = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "optionCell")
        let containerView: UIView = UIView(frame: CGRect(x: self.view.frame.width + 5, y: 0, width: 135.0, height: CGFloat(44 * 8)))
        containerView.center.y = self.view.center.y + 32
//        containerView.layer.shadowColor = UIColor.blackColor().CGColor
        tableView.tableFooterView = UIView()
        
        containerView.layer.shadowColor = UIColor(red: 135/255, green: 135/255, blue: 135/255, alpha: 1).CGColor
        containerView.layer.shadowOffset = CGSize(width: -4, height: 4)
        containerView.layer.shadowOpacity = 0.5
        containerView.clipsToBounds = false
        containerView.layer.cornerRadius = 10
        containerView.addSubview(tableView)
        return containerView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print("详情页面",self.id)

        detailTableView.tableFooterView = UIView(frame: CGRectZero)
        detailTableView.estimatedRowHeight = 50
        detailTableView.rowHeight = UITableViewAutomaticDimension
        
        titleItem.title = medicineName
        
        //药品请求过来的
        if self.id == 2 {
            getEnterpriseDetailMedicine(enterpriseMedicineType)
        } else {
            if medicineType == "西药" {
                getDataFromWestMedicines()
            }
            else {
                getDataFromChineseMedicines()
            }
        }
        
        let customBarItem = NSBundle.mainBundle().loadNibNamed("CustomBarItem", owner: nil, options: nil).first as! CustomBarItem
        customBarItem.frame.size = CGSize(width: 70.0, height: 30.0)
        customBarItem.shareAction = share
        customBarItem.collectionAction = collection
        let navigationItemBar = UIBarButtonItem(customView: customBarItem)
        titleItem.rightBarButtonItem = navigationItemBar
        self.view.addSubview(optionsTableView)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = true
    }
    
    func setUpEnterpriseMedicine() {
        if self.enterpriseMedicineType == 4 { //西药
//            let fieldName = ["enterpriseName",]
        }
    }
    
    func getDataFromChineseMedicines() {
        db.open()
        if let medicineResult = db.executeQuery("select * from chinese_medicine where id = ?", medicineID) {
            let fieldName = ["name", "annouce","category","content","efficacy","manual","preparations","store"]
            titles = ["【名称】", "【药品禁忌】", "【药品分类】", "【药品成分】", "【药品疗效】", "【使用说明】", "【制剂与规格】", "【成人用量】", ]
            while(medicineResult.next()) {
                for field in fieldName {
                    let information = medicineResult.stringForColumn(field)
                    contents.append(information)
                }
            }
        }
        db.close()
    }
    
    func getDataFromWestMedicines() {
        db.open()
        
        if let medicineResult = db.executeQuery("select * from west_medicine where id = ?", medicineID) {
            let fieldName = ["name", "other_name", "ADRS", "content", "current_application", "dose_explain", "interaction", "manual", "pharmacolo", "preparations", "warn"]
            titles = ["【名称】", "【其它名称】", "【不良反应】", "【药品成分】", "【临床应用】", "【使用说明】", "【药物相互作用】", "【成人用量】", "【药效学】", "【制剂与规格】", "【注意事项】"]
            while(medicineResult.next()) {
                for field in fieldName {
                    let information = medicineResult.stringForColumn(field)
                    contents.append(information)
                }
            }
        }
        
        db.close()
    }
    
    func getTitle(information: String) -> (String, Int) {
        var index = 0
        for character in information.characters {
            index++
            if (character == "：" || character == "］") {
                break
            }
        }
        let subStr = information.substringToIndex(information.startIndex.advancedBy(index))
        return (subStr, index)
    }

    
    @IBAction func showOrHideMenu(sender: UIButton) {
        if !menuIsShow {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.optionsTableView.frame.origin.x = self.view.frame.width - 135.0
            })
        }
        else {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.optionsTableView.frame.origin.x = self.view.frame.width + 5
            })
        }
        menuIsShow = !menuIsShow
    }
    
    func share() {
        var shareURL = ""
        if medicineType == "西药" {
            shareURL = "http://112.74.131.194:8080/MedicineProject/share/medicine/2/\(medicineID)"
        }
        else {
            shareURL = "http://112.74.131.194:8080/MedicineProject/share/medicine/1/\(medicineID)"
        }
        let shareParames = NSMutableDictionary()
        print(shareURL)
        shareParames.SSDKSetupShareParamsByText("医药信息－－\(medicineName)",
            images : UIImage(named: "logo"),
            url : NSURL(string: shareURL),
            title : "分享自医药汇",
            type : SSDKContentType.Auto)
        //2.进行分享 ，添加了多少个进白名单，弹框就有多少个。
        ShareSDK.showShareActionSheet(self.view, items:nil, shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, Bool end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("分享成功")
            case SSDKResponseState.Fail:    print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("分享取消")
                
            default:
                break
            }
        }
    }
    
    //MARK: 收藏功能
    func collection() {
        print("xxx")
    }

}

extension MedicineDetailController: UITableViewDataSource {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.id == 2{
            if self.enterpriseMedicineType == 4 {
                return enterpriseWesternMedicine.count //西药
            }
                return enterpriseTraditionMedicine.count //中药
        } else {
            return titles.count
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if tableView.tag == 501 {
            let cell = tableView.dequeueReusableCellWithIdentifier("optionCell", forIndexPath: indexPath)
            if self.id == 2 { //还需要判断企业过来的是中药还是西药
                if self.enterpriseMedicineType == 4 { //西药
                    cell.textLabel?.text = enterpriseWesternMedicine[indexPath.row].name
                }else if self.enterpriseMedicineType == 3 { //中药
                    cell.textLabel?.text = enterpriseTraditionMedicine[indexPath.row].name
                }
            }
            else {
                cell.textLabel?.text = titles[indexPath.row]
            }
            return cell
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier("detailCell", forIndexPath: indexPath) as! DetailCell
        if self.id == 2 {
            if self.enterpriseMedicineType == 4 { //西药
                cell.titleLabel.text = enterpriseWesternMedicine[indexPath.row].name
                cell.contentLabel.text = enterpriseWesternMedicine[indexPath.row].content
            }else if self.enterpriseMedicineType == 3 { //中药
                cell.textLabel?.text = enterpriseTraditionMedicine[indexPath.row].name
                cell.contentLabel.text = enterpriseTraditionMedicine[indexPath.row].content
            }
        } else {
            cell.titleLabel.text = titles[indexPath.row]
            cell.contentLabel.text = contents[indexPath.row]
        }
        return cell
    }
}

extension MedicineDetailController: UITableViewDelegate {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if tableView.tag == 501 {
            detailTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
        }
       
        if menuIsShow == true {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.optionsTableView.frame.origin.x = self.view.frame.width + 5
            })
            menuIsShow = false
        }
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if let _ = scrollView.viewWithTag(502) {
            if menuIsShow == true {
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.optionsTableView.frame.origin.x = self.view.frame.width + 5
                })
                menuIsShow = false
            }
        }
    }
}

//MARK:请求企业药品详细内容
extension MedicineDetailController {
    func getEnterpriseDetailMedicine(enterpriseMedicineType : Int) {
        let detailURL = "112.74.131.194:8080/MedicineProject/App/user/getEnterMedicine"
        Alamofire.request(.POST, detailURL, parameters: ["id": self.medicineID,"type":enterpriseMedicineType], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (_, _, result) -> Void in
            
            if let value = result.value {
                //先是二级药品的数据
                if let Medicine = value["entity"] as? [Dictionary<String, AnyObject>] {
                    for item in Medicine {
                        if enterpriseMedicineType == 4 { //西药
                            let detailMedicine = EnterpriseDetailWesternMedicine(entity: item)
                            self.enterpriseWesternMedicine.append(detailMedicine)
                        } else if enterpriseMedicineType == 3 { //中药
                            let detailMedicine = EnterpriseDetailTraditionMedicine(entity: item)
                            self.enterpriseTraditionMedicine.append(detailMedicine)
                        }
                    }
                }
                //再子类药品的数据
                NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                    self.detailTableView.reloadData()
                    MBProgressHUD.hideHUDForView(self.view, animated: true)
                })
            }
            else {
                //MARK: something error
            }
        }
    }
    
}